#include "WASDCamera.h"

#include <iostream>

using namespace std;
#include <d3d11.h>
#include <d3dx11.h>
#include <xnamath.h>
#include "..\Utils\Globals.h"
#include "..\Utils\KeyboardHandler.h"
#include "..\Utils\MouseHandler.h"

using namespace Utils;

namespace Cameras{
	
	WASDCamera::WASDCamera(){
		this->rotationSpeed = 0.5f;
		this->movementSpeed = 5.0f;
	}

	void WASDCamera::Update(float dt){
		
		rotation = HandleMouseMovement(dt);		
		forward = XMVector3TransformCoord(initialForward, rotation);
		right = XMVector3TransformCoord(initialRight, rotation);
		up = XMVector3TransformCoord(initialUp, rotation);

		HandleKeyboardMovement(dt);

		if (changed){
			viewMatrix = XMMatrixLookAtLH(position, position + forward, up);
			changed = false;
		}
	}

	void WASDCamera::HandleKeyboardMovement(float dt)
	{		
		if (KeyboardHandler::IsKeyDown(DIK_W))
		{
			position += forward * dt * movementSpeed;
			changed = true;
		}
		if (KeyboardHandler::IsKeyDown(DIK_S))
		{
			position -= forward * dt * movementSpeed;
			changed = true;
		}
		if (KeyboardHandler::IsKeyDown(DIK_A))
		{
			position -= right * dt * movementSpeed;
			changed = true;
		}
		if (KeyboardHandler::IsKeyDown(DIK_D))
		{
			position += right * dt * movementSpeed;
			changed = true;
		}
	}

	XMMATRIX WASDCamera::HandleMouseMovement(float dt){

		if (MouseHandler::MouseState.lX  != 0 || MouseHandler::MouseState.lY != 0 ){
			changed = true;

			totalYaw += ((float)MouseHandler::MouseState.lX / aspectRatio ) * dt * rotationSpeed;
			totalPitch -= ((float)MouseHandler::MouseState.lY / aspectRatio )* dt * rotationSpeed;

			if(totalYaw < 0.0f)
				totalYaw += XM_2PI;
			else if(totalYaw > XM_2PI)
				totalYaw -= XM_2PI;
		
			if(totalPitch < -XM_PIDIV2+0.1f)
				totalPitch = -XM_PIDIV2+0.1f;
			else if(totalPitch > XM_PIDIV2-0.1f)
				totalPitch = XM_PIDIV2-0.1f;	
		}

		return XMMatrixRotationRollPitchYaw(totalPitch, totalYaw, 0.0f);
	}
		
}